package com.coursebooking.repository;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.coursebooking.model.Course;
import com.coursebooking.model.Teacher;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Mapper
public interface CourseRepository extends BaseMapper<Course> {
    
    @Select("SELECT * FROM course WHERE code = #{code}")
    Course selectByCode(String code);
    
    @Select("SELECT COUNT(*) FROM course WHERE code = #{code}")
    int countByCode(String code);
    
    @Select("SELECT * FROM course WHERE teacher_id = #{teacherId}")
    List<Course> selectByTeacherId(Long teacherId);
    
    @Select("SELECT * FROM course WHERE status = #{status}")
    List<Course> selectByStatus(String status);
    
    @Select("SELECT * FROM course WHERE start_time >= #{startTime} AND end_time <= #{endTime}")
    List<Course> selectByTimeRange(@Param("startTime") LocalDateTime startTime, 
                                  @Param("endTime") LocalDateTime endTime);
    
    @Select("SELECT * FROM course WHERE name LIKE CONCAT('%', #{keyword}, '%') OR description LIKE CONCAT('%', #{keyword}, '%')")
    List<Course> selectByKeyword(@Param("keyword") String keyword);
    
    // 为了保持兼容性，添加包装方法
    default Optional<Course> findByCode(String code) {
        return Optional.ofNullable(selectByCode(code));
    }
    
    default boolean existsByCode(String code) {
        return countByCode(code) > 0;
    }
    
    default List<Course> findByTeacher(Teacher teacher) {
        return selectByTeacherId(teacher.getId());
    }
    
    default List<Course> findByStatus(Course.CourseStatus status) {
        return selectByStatus(status.name());
    }
    
    default List<Course> findByTimeRange(LocalDateTime startTime, LocalDateTime endTime) {
        return selectByTimeRange(startTime, endTime);
    }
    
    default List<Course> findByKeyword(String keyword) {
        return selectByKeyword(keyword);
    }
}